package firebase

import (
	"context"
	"log/slog"

	"firebase.google.com/go/v4"
	"firebase.google.com/go/v4/messaging"
	"google.golang.org/api/option"
)

var backgroundCtx context.Context
var msgClientMap = make(map[string]*messaging.Client)

func getMsgClient(credentials string) *messaging.Client {
	msgClient := msgClientMap[credentials]
	if msgClient == nil {
		backgroundCtx = context.Background()

		//opt := option.WithCredentialsFile("conf/firebase-service-account.json")
		opt := option.WithCredentialsJSON([]byte(credentials))
		defaultApp, err := firebase.NewApp(backgroundCtx, nil, opt)
		if err != nil {
			slog.Error("error initializing app: ", err)
			return nil
		}

		msgClient, err = defaultApp.Messaging(backgroundCtx)
		if err != nil {
			slog.Error("error initializing client: ", err)
			return nil
		}

		msgClientMap[credentials] = msgClient
	}
	return msgClient
}

type FirebaseSvc struct {
	Credentials string `json:"credentials"`
}

func (svc *FirebaseSvc) SendMsgToToken(token string, title string, body string, badge int, data map[string]string) {

	message := &messaging.Message{
		Data: data,
		Notification: &messaging.Notification{
			Title: title,
			Body:  body,
		},
		APNS: &messaging.APNSConfig{
			Payload: &messaging.APNSPayload{
				Aps: &messaging.Aps{
					Badge: &badge,
				},
			},
		},
		Token: token,
	}

	msgClient := getMsgClient(svc.Credentials)
	response, err := msgClient.Send(backgroundCtx, message)
	if err != nil {
		slog.Error(err.Error())
		return
	}

	slog.Debug("Successfully sent message:", response)
}
